package com.gw.vip.server.crontab;

import com.gw.vip.server.service.dao_service.SysArgService;
import com.gw.vip.server.service.DayCutBiz;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * @author GW
 * @description
 * @since 2022-05-07
 */
@Service
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class Crontab {

    private final SysArgService sysArgService;
    private final DayCutBiz dayCutBiz;

    /**
     * 日切
     * 每小时执行
     */
    @Scheduled(fixedDelay = 1000*60*60)
    public void dayCutCrontab(){
        LocalDate clearDate = sysArgService.getClearDate();
        LocalDateTime clearMaxTime = sysArgService.getClearMaxTime();

        //检查清算日期，只处理昨天以前的清算日期
        if (!this.checkClearDay(clearDate)){
            return;
        }

        //设置清算日期
        dayCutBiz.setClearDate(clearDate, clearMaxTime);

        //初始化tmp表
        dayCutBiz.initTmp(clearDate);

        //帐户明细检查
        dayCutBiz.checkAccountTrans(clearDate);

        //总分平衡检查
        dayCutBiz.checkAllAmt(clearDate);

        //交易转历史
        dayCutBiz.toHis(clearDate);

        //开启下一个清算
        dayCutBiz.nextClearReady(clearDate);
    }

    //----------------------------------- 辅助函数 ------------------------------------------//

    /**
     * 检查清算日期，只处理昨天以前的清算日期
     * @param clearDate
     */
    private boolean checkClearDay(LocalDate clearDate) {
        LocalDate yesterday = LocalDate.now().minusDays(1);
        if (clearDate.compareTo(yesterday)>0){
            log.warn("预计清算日期【{}】，目前清算日期【{}】,不符合", yesterday, clearDate);
            return false;
        }
        return true;
    }
}
